//
//  AppDelegate.m
//  Comma
//
//  Created by dlios on 15-1-13.
//  Copyright (c) 2015年 lanou3g.com 蓝鸥科技. All rights reserved.
//
#import <ShareSDK/ShareSDK.h>
#import <TencentOpenAPI/QQApiInterface.h>
#import <TencentOpenAPI/TencentOAuth.h>
#import "WXApi.h"
#import "WeiboSDK.h"
#import <RennSDK/RennSDK.h>
#import "AppDelegate.h"
#import "URLMacro.h"
#import "Reachability.h"
#import "ConnectModel.h"
#import "GlobalMacro.h"
#import "NDetailListViewController.h"
#import "ImageDB.h"
#import "NotificationViewController.h"
#import "HelpViewController.h"
#import "LoginAndRegisterViewController.h"
#import "LoginViewController.h"
#import "ReleaseViewController.h"
#import "LoginAndRegisterViewController.h"
#import "NavigationViewController.h"
#import "AFNetWorkingYU.h"
#import "SchoolModel.h"
#import "PinYinForObjc.h"
#import "ChineseInclude.h"
#import "XGPush.h"

@interface AppDelegate ()
@end
@implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];
    //判断定时器是否销毁过，如果销毁过 那么标记为0（0还代表第一次进入视图），如果添加了定时器，那么标记为1，就不可以再次添加了(杜：信封闪烁小红点)
    NSUserDefaults *timer = [NSUserDefaults standardUserDefaults];
    [timer setObject:@"0" forKey:@"timer"];
    
    
    // 注册推送通知
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0f) {
        [[UIApplication sharedApplication] registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeBadge | UIUserNotificationTypeSound | UIUserNotificationTypeAlert categories:nil]];
        [[UIApplication sharedApplication] registerForRemoteNotifications];
    } else {
        [[UIApplication sharedApplication] registerForRemoteNotificationTypes:UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound | UIRemoteNotificationTypeAlert];
    }
    
    // 初始化信鸽
    [XGPush startApp:2200087612 appKey:@"ITWI64T43B6E"];
   
    
      
    NSUserDefaults *def = [NSUserDefaults standardUserDefaults];
    NSString *login = [def objectForKey:@"login"];
    
    NDetailListViewController *detail = [[NDetailListViewController alloc] init];
    NavigationViewController *nav = [[NavigationViewController alloc] initWithRootViewController:detail];
    // 记录首页的controller, 为了以后不再重新创建对象
    nav.rootController = detail;
    nav.navigationBar.translucent = NO;
    nav.navigationBarHidden = YES;
    LeftViewController *leftViewController=[LeftViewController share];
    _sideViewController = [YRSideViewController share];
    _sideViewController.rootViewController = nav;
    
    _sideViewController.leftViewController = leftViewController;
    _sideViewController.needSwipeShowMenu = YES;
    [_window setRootViewController:_sideViewController];
    NSLog(@"path = %@", NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES));
    if (![login isEqualToString:@"true"]) {
        LoginAndRegisterViewController *login = [[LoginAndRegisterViewController alloc] init];
        UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:login];
        nav.navigationBar.translucent = NO;
        nav.navigationBar.hidden = YES;
        self.window.rootViewController.view.hidden = YES;
        nav.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
        [_window.rootViewController presentViewController:nav animated:YES completion:^{
        }];
    }
    
    // 判断首次进入
    NSUserDefaults * userDefaults = [NSUserDefaults standardUserDefaults];
    BOOL notFirstTime = [[userDefaults objectForKey:@"firstTime"] boolValue];
#warning 测试时删除"!"号
    if (!notFirstTime) {
        // 第一次进入
        [self downloadImage];
    }
    else {
        // 不是第一次进入
        [userDefaults setValue:[NSNumber numberWithBool:YES] forKey:@"firstTime"
         ];
    }
    
    
    [ShareSDK registerApp:@"58ef36f52500"];//字符串api20为您的ShareSDK的AppKey
    
    //添加新浪微博应用 注册网址 http://open.weibo.com
    [ShareSDK connectSinaWeiboWithAppKey:@"3016847923"
                               appSecret:@"8dccda0f60553fc884120ee84608a00b"
                             redirectUri:@"http://www.isu.so"];
    //当使用新浪微博客户端分享的时候需要按照下面的方法来初始化新浪的平台
    [ShareSDK  connectSinaWeiboWithAppKey:@"3016847923"
                                appSecret:@"8dccda0f60553fc884120ee84608a00b"
                              redirectUri:@"http://www.isu.so"
                              weiboSDKCls:[WeiboSDK class]];

    //添加QQ空间应用  注册网址  http://connect.qq.com/intro/login/
    [ShareSDK connectQZoneWithAppKey:@"1103405849"
                           appSecret:@"lqK1dOIJqjYupXF1"
                   qqApiInterfaceCls:[QQApiInterface class]
                     tencentOAuthCls:[TencentOAuth class]];
    
    //添加QQ应用  注册网址  http://open.qq.com/
    [ShareSDK connectQQWithQZoneAppKey:@"1103405849"
                     qqApiInterfaceCls:[QQApiInterface class]
                       tencentOAuthCls:[TencentOAuth class]];
    
    //添加微信应用 注册网址 http://open.weixin.qq.com
    [ShareSDK connectWeChatWithAppId:@"wx09736acf751388c9"
                           wechatCls:[WXApi class]];
    
    //朋友圈
    [ShareSDK connectWeChatSessionWithAppId:@"wx09736acf751388c9" appSecret:@"516c576a174e71d7e10b8011dbd88346" wechatCls:[WXApi class]];
     

    //添加人人网应用 注册网址  http://dev.renren.com
    [ShareSDK connectRenRenWithAppId:@"474785"
                              appKey:@"f051ddadad0747009051de9cc95f8e08"
                           appSecret:@"2cd8a77d1bb549899eeedce5a107fa25"
                   renrenClientClass:[RennClient class]];
    
    
//
    
#pragma mark - 启动页面
    //开机画面
    UIImageView *ima = [[UIImageView alloc] initWithFrame:self.window.bounds];
    ima.image = [UIImage imageNamed:@"750X1334"];
    [self.window addSubview:ima];
    [UIView animateWithDuration:1.5 delay:0 options:UIViewAnimationOptionAllowUserInteraction animations:^{
        ima.alpha = 0;
    } completion:^(BOOL finished) {
        ima.frame = CGRectMake(self.window.bounds.size.width / 2, self.window.bounds.size.height / 2, 0, 0);
    }];

    
    
    
    return YES;
}

#pragma mark - 
#pragma mark 信鸽推送方法


- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
    [XGPush registerDevice:deviceToken];
    NSLog(@"token = %@", [XGPush registerDevice:deviceToken]);
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
    application.applicationIconBadgeNumber = 0;
    NSLog(@"推送消息 ： %@", userInfo);
}

#pragma mark -


- (void)downloadImage
{
    @autoreleasepool {
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            Reachability * reach = [Reachability reachabilityWithHostname:URL_ISUSO_GETEMOTION];
            if ([reach currentReachabilityStatus] != NotReachable)
            {
                id resultData = [ConnectModel connectModelWithUrl:URL_ISUSO_GETEMOTION];
                if ([resultData isKindOfClass:[NSData class]]) {
                    NSDictionary * resultDic = [NSJSONSerialization JSONObjectWithData:resultData options:NSJSONReadingMutableContainers error:nil];
                    if ([[resultDic objectForKey:@"success"] integerValue
                         ] == 1) {
                        NSInteger numberOfIma = [[resultDic objectForKey:@"total"] longValue];
                        NSArray * imaArr = [resultDic objectForKey:@"rows"];
                        for (int i = 0; i < numberOfIma; i ++) {
                            NSDictionary * imageDic = [imaArr objectAtIndex:i];
                            NSData * imageData = [ConnectModel connectModelWithUrl:[imageDic objectForKey:@"url"]];
                            [imageDic setValue:imageData forKey:@"imaData"];
                            [ImageDB insertIntoActWithDic:imageDic];
                        }
                    }
                }
            }
        });
    }
}
- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
    // 角标清0
    application.applicationIconBadgeNumber = 0;
    
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
- (BOOL)application:(UIApplication *)application
      handleOpenURL:(NSURL *)url
{
    return [ShareSDK handleOpenURL:url
                        wxDelegate:self];
}

- (BOOL)application:(UIApplication *)application
            openURL:(NSURL *)url
  sourceApplication:(NSString *)sourceApplication
         annotation:(id)annotation
{
    return [ShareSDK handleOpenURL:url
                 sourceApplication:sourceApplication
                        annotation:annotation
                        wxDelegate:self];
}

@end
